/**
 * 权限管理状态store
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { useEffect } from 'react';
import { getUserPermissions, getUserRoles, clearPermissionCache } from '@/utils/permissions';

interface PermissionState {
  // 状态
  permissions: string[];
  roles: string[];
  loading: boolean;
  error: string | null;
  lastUpdated: number | null;
  autoRefreshEnabled: boolean;

  // 操作
  loadPermissions: () => Promise<void>;
  loadRoles: () => Promise<void>;
  refreshPermissions: () => Promise<void>;
  clearPermissions: () => void;
  hasPermission: (permission: string) => boolean;
  hasAnyPermission: (permissions: string[]) => boolean;
  hasAllPermissions: (permissions: string[]) => boolean;
  hasRole: (role: string) => boolean;
  enableAutoRefresh: () => void;
  disableAutoRefresh: () => void;
  checkForUpdates: () => Promise<boolean>;
}

export const usePermissionStore = create<PermissionState>()(
  persist(
    (set, get) => ({
      // 初始状态
      permissions: [],
      roles: [],
      loading: false,
      error: null,
      lastUpdated: null,
      autoRefreshEnabled: true,

      // 加载用户权限
      loadPermissions: async () => {
        const { loading } = get();
        if (loading) return;

        set({ loading: true, error: null });

        try {
          const permissions = await getUserPermissions();
          set({
            permissions,
            loading: false,
            lastUpdated: Date.now(),
          });
        } catch (error) {
          console.error('加载权限失败:', error);
          set({
            loading: false,
            error: error instanceof Error ? error.message : '加载权限失败',
          });
        }
      },

      // 加载用户角色
      loadRoles: async () => {
        const { loading } = get();
        if (loading) return;

        set({ loading: true, error: null });

        try {
          const roles = await getUserRoles();
          set({
            roles,
            loading: false,
            lastUpdated: Date.now(),
          });
        } catch (error) {
          console.error('加载角色失败:', error);
          set({
            loading: false,
            error: error instanceof Error ? error.message : '加载角色失败',
          });
        }
      },

      // 刷新权限和角色
      refreshPermissions: async () => {
        // 清除缓存
        clearPermissionCache();
        
        set({ loading: true, error: null });

        try {
          const [permissions, roles] = await Promise.all([
            getUserPermissions(),
            getUserRoles(),
          ]);

          set({
            permissions,
            roles,
            loading: false,
            lastUpdated: Date.now(),
          });
        } catch (error) {
          console.error('刷新权限失败:', error);
          set({
            loading: false,
            error: error instanceof Error ? error.message : '刷新权限失败',
          });
        }
      },

      // 清除权限数据
      clearPermissions: () => {
        clearPermissionCache();
        set({
          permissions: [],
          roles: [],
          loading: false,
          error: null,
          lastUpdated: null,
        });
      },

      // 检查单个权限
      hasPermission: (permission: string) => {
        const { permissions } = get();
        return permissions.includes(permission);
      },

      // 检查是否有任一权限
      hasAnyPermission: (permissions: string[]) => {
        const { permissions: userPermissions } = get();
        return permissions.some(permission => userPermissions.includes(permission));
      },

      // 检查是否有所有权限
      hasAllPermissions: (permissions: string[]) => {
        const { permissions: userPermissions } = get();
        return permissions.every(permission => userPermissions.includes(permission));
      },

      // 检查角色
      hasRole: (role: string) => {
        const { roles } = get();
        return roles.includes(role);
      },

      // 启用自动刷新
      enableAutoRefresh: () => {
        set({ autoRefreshEnabled: true });
      },

      // 禁用自动刷新
      disableAutoRefresh: () => {
        set({ autoRefreshEnabled: false });
      },

      // 检查权限是否有更新
      checkForUpdates: async () => {
        const { autoRefreshEnabled, lastUpdated } = get();

        if (!autoRefreshEnabled) return false;

        // 如果超过1分钟，检查更新
        const oneMinute = 60 * 1000;
        if (!lastUpdated || Date.now() - lastUpdated > oneMinute) {
          try {
            const currentPermissions = get().permissions;
            const newPermissions = await getUserPermissions();

            // 比较权限是否有变化
            const hasChanges = JSON.stringify(currentPermissions.sort()) !== JSON.stringify(newPermissions.sort());

            if (hasChanges) {
              // 权限有变化，更新store
              set({
                permissions: newPermissions,
                lastUpdated: Date.now(),
              });
              return true;
            }
          } catch (error) {
            console.error('检查权限更新失败:', error);
          }
        }

        return false;
      },
    }),
    {
      name: 'permission-store',
      // 只持久化权限和角色数据，不持久化loading状态
      partialize: (state) => ({
        permissions: state.permissions,
        roles: state.roles,
        lastUpdated: state.lastUpdated,
      }),
      // 版本控制
      version: 1,
    }
  )
);

// 权限检查的便捷Hook
export const usePermissionCheck = () => {
  const store = usePermissionStore();
  
  return {
    permissions: store.permissions,
    roles: store.roles,
    loading: store.loading,
    error: store.error,
    lastUpdated: store.lastUpdated,
    
    // 操作方法
    loadPermissions: store.loadPermissions,
    loadRoles: store.loadRoles,
    refreshPermissions: store.refreshPermissions,
    clearPermissions: store.clearPermissions,
    
    // 权限检查方法
    hasPermission: store.hasPermission,
    hasAnyPermission: store.hasAnyPermission,
    hasAllPermissions: store.hasAllPermissions,
    hasRole: store.hasRole,

    // 自动更新相关
    autoRefreshEnabled: store.autoRefreshEnabled,
    enableAutoRefresh: store.enableAutoRefresh,
    disableAutoRefresh: store.disableAutoRefresh,
    checkForUpdates: store.checkForUpdates,
  };
};

// 权限初始化Hook
export const usePermissionInit = () => {
  const { loadPermissions, loadRoles, lastUpdated } = usePermissionCheck();
  
  // 检查是否需要初始化权限
  const needsInit = () => {
    if (!lastUpdated) return true;

    // 如果超过5分钟，需要重新加载（缩短更新间隔）
    const fiveMinutes = 5 * 60 * 1000;
    return Date.now() - lastUpdated > fiveMinutes;
  };

  // 初始化权限
  const initPermissions = async () => {
    if (needsInit()) {
      await Promise.all([loadPermissions(), loadRoles()]);
    }
  };

  return { initPermissions, needsInit };
};

// 权限自动更新Hook
export const usePermissionAutoUpdate = () => {
  const { checkForUpdates, autoRefreshEnabled } = usePermissionCheck();

  useEffect(() => {
    if (!autoRefreshEnabled) return;

    // 设置定时器，每分钟检查一次权限更新
    const interval = setInterval(async () => {
      try {
        const hasUpdates = await checkForUpdates();
        if (hasUpdates) {
          console.log('权限已更新，菜单将自动刷新');
          // 可以在这里触发菜单重新渲染或显示通知
        }
      } catch (error) {
        console.error('自动检查权限更新失败:', error);
      }
    }, 60 * 1000); // 每分钟检查一次

    return () => clearInterval(interval);
  }, [autoRefreshEnabled, checkForUpdates]);

  return { checkForUpdates };
};
